
(function ($) {

    var
        config_map = {
            MSG_TYPE_TEXT: 0,
            MSG_TYPE_VOICE: 1,

            COUNT_DOWN_CNT: 60,

            SEND_MSG_CODE_URL: '/v1/user/sendValidationCode.do',

            COUNT_DOWN_START_EVENT: 'mm_count_down_start',
            COUNT_DOWN_END_EVENT: 'mm_count_down_end',
            
            READY_COLOR: '#10ac86',
            WAITING_COLOR: '#d2d5d9'
        },

        i18n = {
            SEND_TEXT_CODE: languageJson['messagecode_send_text_code'],
            SEND_VOICE_CODE: languageJson['messagecode_send_voice_code'],
            COUNT_DOWN: languageJson['messagecode_count_down'],

            OOPS_MSG: languageJson['messagecode_oops']
        },

        btn_html_template = '' +
            '<span class="{mm_main} sendCode">' +
                '<span class="{mm_ready}" style="display: inline-block">' +
                    '<span class="{mm_send_btn}" style="display: inline-block; cursor: pointer;">' + i18n.SEND_TEXT_CODE + '</span>' +
                    '<span class="{mm_bar}" style="display: none;">&nbsp;&nbsp;|&nbsp;&nbsp;</span>' +
                    '<span class="{mm_voice_btn}" style="display: none; cursor: pointer;">' + i18n.SEND_VOICE_CODE + '</span>' +
                '</span>' +
                '<span class="{mm_waiting}" style="display: none; color: #d2d5d9;">' +
                    '<span class="{mm_count}"></span>' +
                    '<span>' + i18n.COUNT_DOWN + '</span>' +
                '</span>' +
            '</span>',

        btn_html_template_replace_regex = /\{(.+?)}/g;


    function updateUI (inputId, btnClass) {
    	var foo = parseInt($('.'+btnClass).css('width'));
        $('#'+inputId).css('margin-right', '-'+foo+'px');
    }
    
    function readySendButton(that) {
    	$('.'+that.class_map.mm_send_btn)
	        .one('click', function () {

	            if(that.settings.type==13||that.settings.type==72){
                    showCaptchaDialog();
                }else{
                    sendMsgCode.call(that, config_map.MSG_TYPE_TEXT);
                }
	        })
	        .css('cursor', 'pointer');
    
	    $('.'+that.class_map.mm_voice_btn)
	        .one('click', function () {
	            sendMsgCode.call(that, config_map.MSG_TYPE_VOICE);
	        })
	        .css('cursor', 'pointer');
	
	    $('.' + that.class_map.mm_ready).css('color', config_map.READY_COLOR);
    }

    function sendMsgCode (msgType) {

        var that = this;
        
        $('.' + that.class_map.mm_ready).css('color', config_map.WAITING_COLOR);
        
        $('.'+that.class_map.mm_voice_btn).off('click').css('cursor', 'auto');
        $('.'+that.class_map.mm_send_btn).off('click').css('cursor', 'auto');
        
        $('#'+that.settings.inputId).focus();

        //发送验证码
        var params = {
            type: that.settings.type,
            msgType: msgType,
            inputId: that.settings.inputId,
            phoneErrorId: that.settings.phoneErrorId
        };

//        if(params.type == 72){
//        	params.showCaptcha = $('#isCaptcha').val().trim();
//        	params.captcha = $('#captcha').val().trim();
//        }
        if (that.settings.phone) {
            params.phone =
                typeof that.settings.phone === 'function'
                    ? that.settings.phone()
                    : $('#' + that.settings.phoneId).val().trim();
        }
        if (that.settings.areaCode) {
            params.areaCode =
                typeof that.settings.areaCode === 'function'
                    ? that.settings.areaCode()
                    : $('#' + that.settings.areaCodeId).val().trim();
        }

        $.ajax({
            url: config_map.SEND_MSG_CODE_URL,
            data: params,
            dataType: 'json',
            type: 'POST',

            success: function (result) {
                if (result.resultCode == 0) {
                    error.resetError(that.settings.inputId);
                    $('.'+that.class_map.mm_main).trigger(config_map.COUNT_DOWN_START_EVENT);
                } else {
                    error.handleError(result);
                    readySendButton(that);
                }
            },

            error: function () {
                error.displayError(that.settings.inputId, i18n.OOPS_MSG);
                readySendButton(that);
            }

        });

    }

    function countDownStart () {

        var that = this;

        $('.'+that.class_map.mm_ready).css('display', 'none');
        $('.'+that.class_map.mm_waiting).css('display', 'inline-block');

        (that.jQuery_map.cnt || (that.jQuery_map.cnt = $('.'+that.class_map.mm_count))).text(config_map.COUNT_DOWN_CNT);

        //updateUI(that.settings.inputId, that.class_map.mm_main);

        //倒计时
        var cnt = config_map.COUNT_DOWN_CNT;
        var timeout = function () {

            if (cnt > 0) {
            	that.jQuery_map.cnt.text(cnt--);
                setTimeout(timeout, 1000);
            } else {
                $('.'+that.class_map.mm_main).trigger(config_map.COUNT_DOWN_END_EVENT);
            }

        };

        setTimeout(timeout, 0);
    }

    function countDownEnd () {

        var that = this;
        if (that.state_map.first) {
            $('.'+that.class_map.mm_bar + ',.'+that.class_map.mm_voice_btn).css('display', 'inline-block');
            that.state_map.first = false;
        }

        $('.'+that.class_map.mm_ready).css('display', 'inline-block');
        $('.'+that.class_map.mm_waiting).css('display', 'none');

        $('.'+that.class_map.mm_count).text('');

        //updateUI(that.settings.inputId, that.class_map.mm_main);

        readySendButton(that);
    }

    function initSendButton (settings) {

        var class_map = {};

        var btn_html = btn_html_template.replace(btn_html_template_replace_regex, function (match, key) {
            return class_map[key] = settings.inputId + '_' + key;
        });

        $('#'+settings.inputId).after(btn_html);        
        //updateUI(settings.inputId, class_map.mm_main);

        var context = {
            settings: settings,
            class_map: class_map,
            state_map: {
                first: true
            },
            jQuery_map: {}
        };

        $('.'+class_map.mm_send_btn)
            .one('click', function () {

                if("updatePwdPhoneCode"!=settings.inputId&&(settings.type==72||settings.type==13)){
                    showCaptchaDialog();
                }else {
                    sendMsgCode.call(context, config_map.MSG_TYPE_TEXT);
                    //countDownStart.call(context);
                }
            });

        $('.'+class_map.mm_main)
            .on(config_map.COUNT_DOWN_START_EVENT, function () {
                countDownStart.call(context);
            })
            .on(config_map.COUNT_DOWN_END_EVENT, function () {
                countDownEnd.call(context);
            });


        $('#sure').click(function (){

            var ranCode = $("#ranCodeInput").val();
            var msgCodeBindBtn = $(".msgCode_mm_count");
            var ranCodeSubmit = $("#ranCodeSubmit");
            var desc='';
            var type =1;
            //因为是公用的，所以通过页面标签属性值判断是哪种类型的验证码
            //1忘记密码，2注册
                type=$("#sure").attr("type");



            // 判断是否存于短信1分钟冻结状态
            if(msgCodeBindBtn.val().match(/^[0-9].+$/)){
                return ;
            }

            if(ranCode.length<4){
                //msgCodeBindBtn.disabled = true;
                //inputNbgDisabledTrue("msgCodeBindBtn");
                //return ;
                desc= languageJson['smsisincorrect'];
            }else if(ranCode.length==4){
                // 校验验证码
                url = "/user/checkCaptcha.do?type="+type+"&random="+Math.round(Math.random()*100);
                var param={ranCode:ranCode};
                jQuery.post(url,param,function(resultData){
                    var result = eval('(' + resultData + ')');
                    if(result!=null){
                        var data = result.resultCode;
                    }else{
                        var data = -2;
                    }

                    if(data==1){
                        desc = "";
                        //msgCodeBindBtn.disabled = false;
                        //inputNbgDisabledFalse("msgCodeBindBtn");
                        $(".codeLi").hide();
                        $("."+class_map.mm_ready).hide();
                        //dialogBoxHidden();
                        $("."+class_map.mm_waiting).show();

                        sendMsgCode.call(context, config_map.MSG_TYPE_TEXT);
                        //countDownStart.call(context);
                    }else if(data==-1){

                        desc = languageJson['smsisincorrect'];
                        //ranCodeSubmit.attr("disabled",true);
                    }else if(data==-2){

                        desc = languageJson['smsisincorrect'];
                    }else{

                        //ranCodeSubmit.attr("disabled","true");
                        desc= languageJson['smsisincorrect'];
                    }
                    if($("#codeLiTips")!=null){
                        $("#codeLiTips").html(desc);
                        window.setTimeout(function(){
                            jQuery("#codeLiTips").html(" ");
                        },5000);
                    }

                });

            }else if(ranCode.length>4){
                //desc = get$("thecodeformatincorrect");
                //msgCodeBindBtn.disabled = true;
                //inputNbgDisabledTrue("msgCodeBindBtn");
                desc= languageJson['smsisincorrect'];
            }
            if(desc!=null){
                $("#codeLiTips").html(desc);
                window.setTimeout(function(){
                    jQuery("#codeLiTips").html(" ");
                },5000);
            }


            return;
        });
    }


    function showCaptchaDialog() {
        phoneNum = $("#phoneNum").val();
        areaCode = $("#nationtext").val();
        desc="";

        if($.trim(phoneNum)==''){
            desc=languageJson['coincommonjs22'];
        }
        else if(areaCode=='86'){
            if(!checkMobile(phoneNum)){
                desc=languageJson['coincommonjs23'];
            }
        }else if(areaCode!='86'){
            if(!checkPositiveNumber(phoneNum)){
                desc=languageJson['coincommonjs23'];
            }
        }
        if(desc!=""){
            $("#phoneNumError").html(desc);
        }else {
            $(".codeLi").show();

        }
    }


    function checkPositiveNumber(num){
        filter=/^([1-9][0-9]*|0)$/;
        if(!filter.test(trim(num))){
            return false;
        }else{
            return true;
        }
    }

    function checkMobile(mobile){
        filter=/^1[3|4|5|8|7][0-9]\d{8}$/;
        if(!filter.test(trim(mobile))){
            return false;
        }else{
            return true;
        }
    }
    


    $.fn.initMessageCode = function (config) {

        var settings = {
            inputId: this.attr('id'),
            phone: false,
            areaCode: false,
            phoneId: 'phone',
            areaCodeId: 'areaCode',
            phoneErrorId: this.attr('id')
        };
        $.extend(settings, config);

        initSendButton(settings);
        
        return {
        	reset: function (config) {
        		$.extend(settings, {
        			phone: false,
        			areaCode: false,
        			phoneId: 'phone',
        			areaCodeId: 'areaCode'
        		});
        		$.extend(settings, config);
        	}
        };

    };

})(jQuery);

function closeCaptchaDialog() {
    $(".codeLi").hide();
}